package main

import (
	"http"
	"log"
	"url"
	"cloud9lib.googlecode.com/hg/rest"
	"cloud9lib.googlecode.com/hg/index"
	"cloud9lib.googlecode.com/hg/sync"
)

func onUpdate(bucket string) {

	dest, err := index.WhereIs(bucket)

	if err != nil {
		log.Println(err)
	}

	desturl, err := url.Parse(dest)

	if err != nil {
		log.Println(err)
	}

	log.Println("muxd: added bucket ", bucket, desturl.String())
	http.Handle("/" + bucket + "/", rest.Log(http.NewSingleHostReverseProxy(desturl)))
}

func main () {

	rest.LogPrefix = "muxd: "

	index.AddMux("http://localhost:8001")

	feed := sync.Feed(index.INDEX_URL, "buckets")
	go feed.Subscribe(0, nil, onUpdate)

	http.Handle("/", rest.Log(http.NotFoundHandler()))
	http.ListenAndServe(":8001", nil)


}
